import { Register, SendToRender } from './ipcRequest'
const { ipcMain } = require('electron')
import * as iconvLite from 'iconv-lite'
import Datastore from 'nedb'
import path from 'path'
import { app } from 'electron'
const configDir = app.getPath('userData')
var confPath = path.join(configDir, 'db/device.db')
console.log('配置db路径', confPath)
var data_db = new Datastore({
  autoload: true,
  filename: confPath
})
var defaultArgs = `{
  "DocName":"buildSetting",
  "ServerAddr": "正式服",
  "basepath": "拖动工程目录到此...",
  "description": "lalalal",
  "platform": "android",
  "version": "1.0.0"
}`
const doc = JSON.parse(defaultArgs)
var buildArgs

var init = async function(mainWindow) {
  Register(mainWindow)
  buildArgs = await ReadConfig()
  console.log('参数如下', buildArgs)
  setTimeout(() => {
    SendToRender('readConfigToRender', buildArgs)
  }, 1000)
  ipcMain.on('readConfigToRender', (event, arg) => {
    if (buildArgs) {
      SendToRender('readConfigToRender', buildArgs)
    }
  })
}
var findConfig = function() {
  const promise = new Promise(function(resolve, rejecte) {
    data_db.find({ DocName: 'buildSetting' }, function(err, docs) {
      if (err) {
        rejecte(err)
      } else {
        resolve(docs)
      }
    })
  })
  return promise
}
var ReadConfig = async function() {
  var result = doc
  var res = await findConfig()
  if (Array.prototype.isPrototypeOf(res) && res.length !== 0) {
    result = res[0]
  } else {
    data_db.insert(doc, function(err, new_doc) {
      'use strict'
      console.log(err, new_doc)
    })
    result = doc
  }
  console.error('查找配置', res)
  return result
}
var WriteConfig = function(args) {
  // 删除多项
  data_db.remove(
    {
      DocName: 'buildSetting'
    },
    {
      multi: true
    },
    (err, ret) => {
      if (err) {
        console.log('删除失败')
      } else {
        args.DocName = 'buildSetting'
        data_db.insert(args, function(err, new_doc) {
          console.log(err, new_doc)
        })
      }
    }
  )

  // data_db.update({ DocName: 'buildSetting' }, args, {}, function(
  //   err,
  //   numReplaced
  // ) {
  //   console.log(err)
  // })
}
var execCmd = function(cmd, content) {
  const spawn = require('child_process').spawn

  const ls = spawn(cmd, content)
  // console.warn(cmd)
  // console.warn(content)
  ls.stdout.on('data', data => {
    const msg = iconvLite.decode(data, 'utf-8')
    const pid = ls.pid
    if (msg.indexOf(pid) > 0) {
      if (msg.indexOf('failed') > 0) {
        SendToRender('stderr', msg)
      } else {
        SendToRender('stdout', msg)
      }
    }
    console.log(msg)
  })
  ls.stderr.on('data', data => {
    const msg = iconvLite.decode(data, 'utf-8')
    const pid = ls.pid
    const index = msg.indexOf(pid)
    if (index > 0 && index < 10) {
      SendToRender('stderr', msg)
    }
    console.error(msg)
  })
  ls.on('close', code => {
    SendToRender('shellClose', code)
  })
}

function getFileList(path, callback) {
  var walk = require('walk')
  var files = []
  var dirs = []
  var size = 0

  var walker = walk.walk(path, { followLinks: false })

  walker.on('file', function(roots, stat, next) {
    if (stat.name.indexOf('.png') > 0) {
      files.push(roots + '/' + stat.name)
      size = size + stat.size
      // SendToRender('stdout', '发现图片：' + roots + '/' + stat.name + '\n')
    }
    next()
  })

  walker.on('directory', function(roots, stat, next) {
    // console.log('目录 ' + stat.name)
    if (stat.name !== '.svn') {
      dirs.push(roots + '/' + stat.name)
    } else {
      console.log('忽略svn目录')
    }
    next()
  })
  walker.on('end', function() {
    // console.log('files ' + files)
    // console.log('dirs ' + dirs)
    SendToRender('stdout', '\n文件总数:' + files.length + '\n')
    SendToRender('stdout', '文件总大小:' + size / (1024.0 * 1024.0) + 'MB\n')
    callback(files)
  })
}
var compressPng = function(file) {
  const content = (() => {
    const t = []
    t.push('--force')
    t.push(file)
    t.push('--ext')
    t.push('.png')
    return t
  })()
  var cmd = '/Users/macmini123/Documents/pngquant/pngquant'
  execCmd(cmd, content)
}

export { init, ReadConfig, execCmd, WriteConfig, getFileList, compressPng }
